﻿using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;

namespace ZBZH_Manage_Order.Controllers.SystemSettings
{
    public class MerDefinitionController : Controller
    {
        //
        // GET: /MerDefinition/
         
        ServiceReference1.Service1Client wsdcser = new ServiceReference1.Service1Client();  
        ZHHQSERVICE.Service1Client service = new ZHHQSERVICE.Service1Client();
        public ActionResult Index()
        {
            return View();
        }
        #region 商户列表grid
        /// <summary> 
        /// 获取商户 
        /// </summary>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult GetAllAccount(JqGridParam jqgridparam)
        {
            try
            {
                Page<View_Order_MerSet> page= new Page<View_Order_MerSet>();
                List<Model.View_Order_MerSet> List = new List<Model.View_Order_MerSet>();
                string result = wsdcser.GetOrder_Mer(GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    List = ParseClass<Model.View_Order_MerSet>.JsonList(jieguo);//解析返回的结果
                    jqgridparam.records = List.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows =page.FindListPage(List, ref jqgridparam)//返回当前页的数据
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = List
                    };
                    return Json(data);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 获取商户类型
        /// <summary>
        /// 获取商户类型
        /// </summary>
        /// <returns></returns>
        public ActionResult getmertype()
        {
            List<Basic_Dict_T> ls = new List<Basic_Dict_T>();
            ls = PublicMethod.GetDict.GetList(34);

            // 添加全部选项按钮
            Basic_Dict_T add = new Basic_Dict_T();
            add.DictName = "全部";
            add.DictKey = "-1";
            ls.Add(add);
            return Json(ls, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 新增商户
        //新增商户操作
        public ActionResult addMer(Model.View_Order_MerSet meradd, string addersss)
        {
            try
            {
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                int uid = user.OperID;
                string json=meradd.ToJson();
                //string adderss = wsdcser.UpdateMerSendAdd(meradd.MerID, addersss, GetYZM._YZM, 1);//送餐地址
                string result = wsdcser.SetOrder_Mer(uid,json,1,"",1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                //JObject add = JObject.Parse(adderss);//将服务返回的结果进行优化
                //string bsadd = add["BS"].ToString();
                if (bs == "1")
                {
                    return Content("OK");
                }
                else
                {
                    return Content("False");
                }
            }
            catch (Exception)
            {
                //return null;
                return RedirectToAction("LoginPage", "Login");  //czx，修改为登录者的Session异常时，直接跳转到登录页面
            }
        }
        #endregion

        #region 允许消费范围
        /// <summary>
        /// 获取允许消费范围
        /// </summary>
        /// <returns></returns>
        public ActionResult getdep()
        {
            try
            {
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                List<TreeJsonEntity> TreeList = new List<TreeJsonEntity>();
                //int uid= user.OperID;
                string result = service.GetDepatMentNoValidate(GetYZM._YZM, 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<ZBZH_Manage_Order.Models.Basic_Department_T> ls = new List<ZBZH_Manage_Order.Models.Basic_Department_T>();
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() == "1")//返回结果正常
                { 
                    IList<JToken> jieguo = jb["rows"].Children().ToList();
                    ls = ParseClass<ZBZH_Manage_Order.Models.Basic_Department_T>.JsonList(jieguo);//解析返回的结果
                    foreach (ZBZH_Manage_Order.Models.Basic_Department_T item in ls)
                    {
                        bool hasChildren = false;
                        IList childnode = ls.FindAll(t => t.DepParentID == item.DepID);
                        if (childnode.Count > 0)
                        {
                            hasChildren = true;
                        }
                        TreeJsonEntity tree = new TreeJsonEntity();
                        tree.id = item.DepID;
                        tree.text = item.DepName;
                        tree.value = item.DepID;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.hasChildren = hasChildren;
                        tree.parentId = item.DepParentID;
                        TreeList.Add(tree);
                    }
                    string a = TreeList.TreeToJson();
                    return Content(TreeList.TreeToJson());
                }
                else
                {
                    return Json(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        #region 修改商户信息
        public ActionResult UpdateMer(Model.View_Order_MerSet merupdate, string addersss)
        {
            Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
            try
            {
                int uid = user.OperID;
                merupdate.MerState = 1;
                string json = merupdate.ToJson();
                string adderss = wsdcser.UpdateMerSendAdd(merupdate.MerID, addersss, GetYZM._YZM, 1);//送餐地址
                string result = wsdcser.SetOrder_Mer(uid,json,2,"",1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化

                JObject add = JObject.Parse(adderss);//将服务返回的结果进行优化
                string bsadd = add["BS"].ToString();

                string bs = searcho["BS"].ToString();
                if (bs == "1" && bsadd == "1")
                {
                    return Content("OK");
                }
                else
                {
                    return Content("False");
                }
            }
            catch(Exception)
            {
                //return null;            
                return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                
            }
        }
        #endregion

        #region 删除商户
        public ActionResult deletemer(Model.View_Order_MerSet delmer)
        {
            Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
            try
            {
                int uid = user.OperID;
                delmer.MerState = 0;
                string json = delmer.ToJson();
                string result = wsdcser.SetOrder_Mer(uid,json, 3, GetYZM._YZM, 1);//更新用户联系人

                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    return Content("OK");
                }
                else
                {
                    return Content(bs);
                }
            }
            catch (Exception)
            {
                //return null;            
                 return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                
            }
        }
        #endregion

        #region 获取所有商户
        /// <summary>
        /// 获取所有商户
        /// </summary>
        /// <returns></returns>
        public List<View_Order_MerSet> GetAllMer()
        {
            List<View_Order_MerSet> list = new List<View_Order_MerSet>();
            string result = wsdcser.GetOrder_Mer("", 1);
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                if (jieguo.Count > 0)
                {
                    foreach (JToken item in jieguo)
                    {
                        // List<Model.Sys_Component_T> list_com = new List<Model.Sys_Component_T>();
                        List<View_Order_MerSet> newlist = new List<View_Order_MerSet>();
                        View_Order_MerSet m = new View_Order_MerSet();
                        m.DelFormMon = int.Parse(item["DelFormMon"].ToString());
                        m.DelMaxMon = int.Parse(item["DelMaxMon"].ToString());
                        m.DelTime = int.Parse(item["DelTime"].ToString());
                        m.DelType = item["DelType"].ToString();
                        m.DictName = item["DictName"].ToString();
                        m.EvaCount = int.Parse(item["EvaCount"].ToString());
                        m.IsRet = int.Parse(item["IsRet"].ToString());
                        m.LastChanMon = item["LastChanMon"].ToString();
                        m.MerAdr = item["MerAdr"].ToString();
                        m.MerCall = item["MerCall"].ToString();
                        m.MerDep = item["MerDep"].ToString();
                        m.MerName = item["MerName"].ToString();
                        m.MerID = item["MerID"].ToString();
                        m.MerPic = item["MerPic"].ToString();
                        m.MerSort = item["MerSort"].ToString();
                        m.MerState = int.Parse(item["MerState"].ToString());
                        m.MerTxt = item["MerTxt"].ToString();
                        m.OverChanMon = item["OverChanMon"].ToString();
                        m.SalesCount = int.Parse(item["SalesCount"].ToString());
                        m.StarCount = int.Parse(item["StarCount"].ToString());
                        list.Add(m);
                    }
                }
                return list;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 查询商户
        public ActionResult SearchMerDefinition(string DelType, string MerName, string MerAdr, JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.View_Order_MerSet> page = new Page<Model.View_Order_MerSet>();//
                List<View_Order_MerSet> ls = GetAllMer();
                List<Model.View_Order_MerSet> newls = new List<Model.View_Order_MerSet>();//
                if (DelType == "-1")
                {
                    ls = ls.ToList();
                }
                if (DelType != "" && DelType != "-1")
                {
                    ls = ls.Where(i => i.DelType.IndexOf(DelType) != -1).ToList();
                }
                if (MerName != "")
                {
                    ls = ls.Where(i => i.MerName.IndexOf(MerName) != -1).ToList();
                }
                if (MerAdr != "")
                { ls = ls.Where(i => i.MerAdr.IndexOf(MerAdr) != -1).ToList(); }
                jqgridparam.records = ls.Count;//查询的数据总数
                var data = new
                {
                    total = ls.Count,
                    rows = page.FindListPage(ls, ref jqgridparam)//返回当前页的数据 
                };
                return Json(data);
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 获取所有地址
        public ActionResult getAdderss()
        { 
            try
            {
                List<Model.Order_MerSendAdd_T> list_ot = new List<Model.Order_MerSendAdd_T>();
                string result = wsdcser.GetAllMerSendAdd(1, 150, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();
                    if (jieguo.Count > 0)
                    {
                        list_ot = ParseClass<Model.Order_MerSendAdd_T>.JsonList(jieguo);
                    }
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list_ot
                    };
                    return Json(list_ot, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list_ot
                    };
                    return Json(list_ot);
                }
            }
            catch (Exception ex)
            {
                return Content("系统异常" + ex);
            }
        }
        #endregion

        #region 获取改商户下的送餐地址
        public ActionResult getMerAdderss(string MerID)
        {
            try
            {
                List<Model.Order_MerSend_T> list_ot = new List<Model.Order_MerSend_T>();
                string result = wsdcser.GetSendAddFromMerId(1, 150, MerID, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();
                    if (jieguo.Count > 0)
                    {
                        list_ot = ParseClass<Model.Order_MerSend_T>.JsonList(jieguo);
                    }
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list_ot
                    };
                    return Json(list_ot, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list_ot
                    };
                    return Json(list_ot);
                }
            }
            catch (Exception ex)
            {
                return Content("系统异常" + ex);
            }
        }
        #endregion


        //#region 获取当前页数据
        ///// <summary>
        ///// 获取当前页数据
        ///// </summary>
        ///// <param name="list">总的list数据</param>
        ///// <param name="jqgridparam">分页参数</param>
        ///// <returns></returns>
        //public List<Model.View_Order_MerSet> FindListPage(List<Model.View_Order_MerSet> list, ref JqGridParam jqgridparam)
        //{
        //    try
        //    {
        //        List<Model.View_Order_MerSet> RetList = new List<Model.View_Order_MerSet>();
        //        string orderField = jqgridparam.sort;//排序列
        //        string orderType = jqgridparam.order;//排序方式
        //        int pageIndex = jqgridparam.page;//当前页
        //        int pageSize = jqgridparam.rows;//每页行数
        //        int totalRow = jqgridparam.records;//总记录数
        //        int lastIndex = pageIndex * pageSize;//当前页最后一行
        //        if (orderType == "asc")
        //        {
        //            list = (from p in list orderby orderField ascending select p).ToList();
        //        }
        //        else if ((orderType == "desc"))
        //        {
        //            list = (from p in list orderby orderField descending select p).ToList();
        //        }

        //        //如果总行数小于当前页最后一行时 当前页最后一行等于总行数
        //        if (totalRow < lastIndex)
        //        {
        //            lastIndex = totalRow;
        //        }
        //        int fistIndex = (pageIndex - 1) * pageSize;
        //        int j = 0;
        //        for (int i = fistIndex; i < lastIndex; i++)
        //        {
        //            j++;
        //            RetList.Add(list[i]);
        //        }
        //        return RetList;
        //    }
        //    catch (Exception)
        //    {
        //        return null;
        //    }
        //}
        //#endregion

    }
}
